# -*- coding: utf-8 -*-
# @Time    : 2024/1/23  10:38
# @Author  : zhanghao
# @FileName: monitor.py.py
# @Software: PyCharm
"""
    Description: 监控线程
"""
from multiprocessing import Pipe
from threading import Thread
from config.config import Config
from config.logger import Logger
from db.sqlite import Sqlite
from core.worker import Worker

import time


class Monitor(Thread):
    logger = Logger.get()

    config: Config
    conn: Pipe
    sqlite: Sqlite

    def __init__(self, conn: Pipe, config: Config):
        super().__init__()
        self.conn = conn
        self.config = config
        self.sqlite = Sqlite()

    def run(self) -> None:
        # 更新db数据状态
        self.sqlite.updateRunningTask()

        worker = self.startSubProcess()
        while True:
            alive = worker.is_alive()
            if not alive:
                self.logger.info('worker进程掉线，现在重启')
                # 更新db数据状态
                self.sqlite.updateRunningTask()

                worker = self.startSubProcess()

            time.sleep(10)

    # 启动子进程
    def startSubProcess(self):
        worker = Worker(self.conn, self.config)
        worker.start()

        return worker
